package com.xiaoa.gossip.cluster.service.impl;

import com.xiaoa.gossip.cluster.command.CurrentNodeState;
import com.xiaoa.gossip.cluster.service.MetadataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Set;

/**
 * @author luokaichuang
 * @time 2020/6/19
 */
@Service
public class MetadataServiceImpl implements MetadataService {

    @Autowired
    private CurrentNodeState currentNodeState;

    @Override
    public synchronized void doUpdateSlot(Set<Integer> slot) {
        currentNodeState.setSlot(slot);

        addVersion();
    }

    @Override
    public synchronized void doAddMetadata(String key, String value) {
        if (currentNodeState.getMetadata() == null) {
            currentNodeState.setMetadata(new HashMap<>());
        }

        currentNodeState.getMetadata().put(key, value);
        addVersion();
    }

    @Override
    public synchronized void doRemoveMetadata(String key) {
        if (currentNodeState.getMetadata() == null) {
            currentNodeState.setMetadata(new HashMap<>());
        }

        if (currentNodeState.getMetadata().containsKey(key)) {
            currentNodeState.getMetadata().remove(key);
        }
        addVersion();
    }

    private void addVersion() {
        currentNodeState.setDataVersion(currentNodeState.getDataVersion() + 1);
    }
}
